package com.wee.fragment;


import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;

import com.bigtotoro.util.SharedPreferencesUtil;
import com.bigtotoro.widgets.AppProgressBar;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.wee.aircoach_user.Constant;
import com.wee.aircoach_user.MyTestPlanActivity;
import com.wee.aircoach_user.PhysicalTestActivity;
import com.wee.aircoach_user.R;
import com.wee.entity.MD5Util;
import com.wee.entity.Point;
import com.wee.entity.User_detail;


public class tab_FragmentTest3 extends Fragment implements  View.OnClickListener{

    private View mMainView;
	private ImageButton btn;
	private TextView start_txt,num_num;
	View rootView;
	private  int reclen;
	private LinearLayout qw;
	private int value2 = -1;
	//第一个动作的成绩
	private int value0=-1;
	//第二个动作的成绩
	private int value1=-1;
    private int number;

	private String user_main;
	private User_detail data1;

	public static final int MSG_TIME_SRART = 1;
	public static final int MSG_TIME_RUNNGIN = 2;
	public static final int MSG_TIME_END = 3;
	public static final int MSG_TIME_READ = 4;

	private int timeValue = 0;
	private TimeTask task;

    private User_detail detail;

	String  user_birth ;
    String  user_gender;

	private Handler mHandler = new Handler(){
		/**测试线程记录数据 timeValue 为记录次数 一秒加一
		 * 因为不是俯卧撑运动所以直接得到start_txt 数据*/
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			String text = "";
			if(msg.what == MSG_TIME_SRART){
				/***应为60s*/
				timeValue=Constant.scend;
				text = timeValue +"";
			}else if(msg.what == MSG_TIME_END){
				/**d调用弹窗  得出最后的结果*/
			try{
				dialog();
			    btn.setVisibility(View.VISIBLE);
			     }catch (Exception e){}
			}else if(msg.what == MSG_TIME_RUNNGIN){
			num_num.setVisibility(View.VISIBLE);
				qw.setBackgroundResource(R.drawable.s_top);
				timeValue--;
				text = timeValue +"";
				num_num.setText(""+text);
				if (timeValue==1){
					task.stopTask();

				}
			}else if(msg.what ==MSG_TIME_READ){
				start_txt.setClickable(false);
				reclen--;
				num_num.setText(""+reclen);
				if(reclen==0){
					num_num.setVisibility(View.GONE);
					qw.setBackgroundResource(R.drawable.s_top);
				}
			}

		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.zice_fragment3, container, false);//���������ļ�
          init();
		return rootView;
	}

	private void  dialog(){
		start_txt.setClickable(true);
		qw.setBackgroundResource(R.drawable.again);
		NumberPicker mPicker = new NumberPicker(getActivity());
		mPicker.setMinValue(0);
		mPicker.setValue(20);
		mPicker.setMaxValue(60);
		mPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

			@Override
			public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
				// TODO Auto-generated method stub
				num_num.setText(String.valueOf(newVal));
				number = Integer.parseInt(String.valueOf(newVal));

				updateTestValue(number);
			}
		});

		AlertDialog mAlertDialog = new AlertDialog.Builder(getActivity())
				.setTitle("体能测试").setView(mPicker).setPositiveButton("ok",null).create();
		mAlertDialog.show();
	}

	private void init() {
		user_gender=SharedPreferencesUtil.get(getActivity(),Constant.GENDER);
		if(user_gender!=null){
			if(user_gender.equals("male")){
				ImageView imageView = (ImageView)rootView.findViewById(R.id.bg_3);
				ImageLoader.getInstance().displayImage("drawable://" + R.drawable.fuwocheng_nan, imageView);
			}else{
				ImageView imageView = (ImageView)rootView.findViewById(R.id.bg_3);
				ImageLoader.getInstance().displayImage("drawable://" + R.drawable.yangwo_nv, imageView);
			}
		}
		ImageView imageView1 = (ImageView)rootView.findViewById(R.id.bottom);
		ImageLoader.getInstance().displayImage("drawable://" + R.drawable.white_bottom, imageView1);

		//切换背景
		qw= (LinearLayout) rootView.findViewById(R.id.qw);
		//完成按钮
		btn=(ImageButton)rootView.findViewById(R.id.btn1);
		btn.setOnClickListener(this);
		//开始测试
		start_txt=(TextView)rootView.findViewById(R.id.btn_start);
		start_txt.setOnClickListener(this);
		num_num=(TextView)rootView.findViewById(R.id.num_num);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_start:
				start_txt.setClickable(false);
				try{
					reclen=4;
					qw.setBackgroundResource(R.drawable.beg_in);
					task = new TimeTask();
					task.start();
				}catch(Exception r){

				}
				break;
			// 完成的话 把数据传递到 成绩页面然后 跳掉那个页面
			case R.id.btn1:
				try{
				if (value2!=-1){
					/**跳转 并传递数据*/
					uploadTest();
				}
				}catch (Exception e){

				}
				break;
			/**重新测试*/
			default:
		}
	}
   private void gethttp(){
	   int exact=  SharedPreferencesUtil.getInt(getActivity(), Constant.USERTIME);
	   int  it=  SharedPreferencesUtil.getInt(getActivity(), Constant.USERID);
	   user_main=Constant.USER_DETAIL+ MD5Util.md5(exact)+"&id="+it+"";
	   HttpUtils httpUtils = new HttpUtils();
  AppProgressBar.checkAndCreateProgressBar(getActivity());
	   httpUtils.send(HttpRequest.HttpMethod.GET, user_main,
			   new RequestCallBack<String>() {
				   @Override
				   public void onSuccess(ResponseInfo<String> responseInfo) {

					   String str = responseInfo.result;
					   Gson gs = new Gson();
					   JsonObject jo = gs.fromJson(str, JsonObject.class);
					   JsonElement je = jo.get("status");
					   String status = je.getAsString();
					   if ("ok".equals(status)) {
						   JsonObject object = jo.getAsJsonObject("data");
						   try {
							   data1 = gs.fromJson(object, User_detail.class);
							   String gender = data1.getGender();
							   String birth = data1.getBirthday();
							   SharedPreferencesUtil.set(getActivity(), Constant.GENDER, gender);
							   SharedPreferencesUtil.set(getActivity(), Constant.BIRTHDAY, birth);
							   AppProgressBar.closeProgressBar();
							   /**传递参数**/
						   } catch (Exception r) {
							   AppProgressBar.closeProgressBar();
						   }
					   }
				   }

				   @Override
				   public void onFailure(HttpException e, String s) {
					   AppProgressBar.closeProgressBar();
					   System.out.println(e.getMessage());
				   }
			   });

   }

	private void updateTestValue(int value){
		value2 = value;
	}
	public class TimeTask implements Runnable{
		private Thread task;
		private boolean isStop = false;
		public TimeTask(){
			task = new Thread(this);
		}
		@Override
		public void run() {
			mHandler.sendEmptyMessage(MSG_TIME_SRART);
			while (!isStop){
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if (reclen>0){
					mHandler.sendEmptyMessage(MSG_TIME_READ);
				}else{
					mHandler.sendEmptyMessage(MSG_TIME_RUNNGIN);
				}
			}
			mHandler.sendEmptyMessage(MSG_TIME_END);
		}
		public void start(){
			task.start();
		}

		public void stopTask(){
			isStop = true;
		}
	}
	private void uploadTest() {
		gethttp();
		PhysicalTestActivity.FragmentArguments args = ((PhysicalTestActivity) getActivity()).setFragmentArguments();
		if (args.value0 != null) {
			value0 = args.value0;
		} else {
			value0 = -1;
		}
		if (args.value1 != null) {
			value1 = args.value1;
		} else {
			value1 = -1;
		}
		if (value0 == -1) {
			Toast.makeText(getActivity(), "平静心率未测试", Toast.LENGTH_SHORT).show();
			return;
		}
		if (value1 == -1) {
			Toast.makeText(getActivity(), "屏息时间未测试", Toast.LENGTH_SHORT).show();
			return;
		}
		if (value2 == -1) {
			Toast.makeText(getActivity(), "力量专项未测试", Toast.LENGTH_SHORT).show();
			return;
		}

/**提价数据*/
		        user_gender=SharedPreferencesUtil.get(getActivity(),Constant.GENDER);
		        user_birth=SharedPreferencesUtil.get(getActivity(),Constant.BIRTHDAY);
            if(user_gender!=null||user_birth!=null) {
				int exact=  SharedPreferencesUtil.getInt(getActivity(), Constant.USERTIME);
	          HttpUtils http = new HttpUtils();
				AppProgressBar.checkAndCreateProgressBar(getActivity());
	           http.send(HttpRequest.HttpMethod.GET,
			   Constant.USER_TICE + "?token=" +MD5Util.md5(exact)+ "&gender=" + user_gender + "" + "&heart=" + value0 + "&breath=" + value1 + "&strenth=" + value2 + "&birth=" + user_birth + "",
			new RequestCallBack<String>() {
				@Override
				public void onLoading(long total, long current, boolean isUploading) {
				}
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					String str = responseInfo.result;
					Gson gs = new Gson();
					JsonObject jo = gs.fromJson(str, JsonObject.class);
					JsonElement je = jo.get("status");
					String status = je.getAsString();
					if ("ok".equals(status)) {
						try{
						JsonObject object = jo.getAsJsonObject("data");
						Point list1 = gs.fromJson(object, Point.class);
						Intent intent = new Intent(getActivity(), MyTestPlanActivity.class);
						intent.putExtra("name",data1.getName());
						intent.putExtra("Heart", value0+"");
						intent.putExtra("Breath", value1+"");
						intent.putExtra("Strenth", value2+"");
						intent.putExtra("He",list1.getHeart()+"");
						intent.putExtra("Br", list1.getBreath()+"");
						intent.putExtra("St", list1.getStrenth()+"");
						intent.putExtra("Percent", list1.getPercent());
						intent.putExtra("Score", list1.getScore());
						startActivity(intent);
						AppProgressBar.closeProgressBar();
						getActivity().finish();
						}catch (Exception r){
							System.out.print("mcmcmcmcmcmcm"+r);
							Toast.makeText(getActivity(), "您的网络不给力啊", Toast.LENGTH_SHORT).show();
							AppProgressBar.closeProgressBar();
						}
					}
					AppProgressBar.closeProgressBar();
				}
				@Override
				public void onStart() {
				}

				@Override
				public void onFailure(HttpException error, String msg) {
					AppProgressBar.closeProgressBar();
					Toast.makeText(getActivity(), "您的网络不给力啊11111", Toast.LENGTH_SHORT).show();
				}
			});
}
	}



}


